package net.rock.controller;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import net.rock.pojo.Comment;
import net.rock.pojo.User;
import net.rock.service.CommentService;
import net.rock.utils.ServiceCaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@EqualsAndHashCode
class ShowCommentJson {
    int id;
    String username;
    String content;
    int score;

    public ShowCommentJson(int id, String username, String content, int score) {
        this.id = id;
        this.username = username;
        this.content = content;
        this.score = score;
    }
}

@RestController
@RequestMapping("/api/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private ServiceCaller serviceCaller;

    @GetMapping("/show")
    public List<ShowCommentJson> show(
        int bookId
    ) {
        List<Comment> comments = commentService.fetchByBookId(bookId);

        return comments.stream().map(comment -> {
            User user = serviceCaller.fetchUserById(comment.getUserId());
            return new ShowCommentJson(
                    comment.getId(),
                    user.getUsername(),
                    comment.getContent(),
                    comment.getScore()
            );
        }).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public void add(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Comment comment
    ) {
        // score 在数据库里面进行了合法性校验
        int userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        comment.setUserId(userId);
        commentService.add(comment);
    }

    @SuppressWarnings("SameParameterValue")
    void del(int bookId) {
        commentService.del(bookId);
    }
}
